<template>
	<view class="container" :style="{background:`url(${pageBg})`,'background-size': '100% 100%'}">
		<top-navigation isShow isFix backIconColor='#000' isBack>
			<template #center-slot>
				<view class="paihang">
					<view class="score">Score: {{ score }}</view>
				</view>
			</template>
		</top-navigation>
		<view class="justify-center align-center">
			<view class="game-grid">
				<view v-for="(cell, index) in cells" :key="index" class="cell">
					<view v-if="cell" class="mole" @tap="hitMole(index)">
						<image class="mouse" src="/mousegame/static/game/mouse.png" mode=""></image>
					</view>
				</view>
			</view>
		</view>

		<view class="btn-box justify-center">
			<text style="color: #FFF;">时间:{{ time }} 秒</text>
		</view>
		<view class="difficulty justify-around">
			<x-btn @tap="startGame" >
				start
			</x-btn>
			<canvas v-show="loading" canvas-id="clockCanvas" id="clockCanvas" type="2d" class="clock"></canvas>
			<x-btn @tap="stop">
				stop
			</x-btn>
			<x-btn v-if="!loading" @tap="difficultyOfSwitching(9)">
				9个
			</x-btn>
			<x-btn v-if="!loading" @tap="difficultyOfSwitching(12)">
				12个
			</x-btn>
			<x-btn v-if="!loading" @tap="difficultyOfSwitching(15)">
				15个
			</x-btn>
		</view>
		<view class="popup flex-col justify-between align-center" v-if="achievementShow">
			<view class="LcdD" style="font-size: 50rpx;">
				成绩
			</view>
			<view class="">
				{{achievement}}
			</view>
		
			<view class="justify-between" style="width: 100%;">
				<x-btn @tap="upload">上传手速</x-btn>
				<x-btn @tap="achievementShow=false">关闭</x-btn>
			</view>
		</view>
		同时出现个数:{{number}}
		<view class="justify-start">
			<x-btn @tap="upload">排行榜</x-btn>
			<view class="" style="flex: 1;">
				<slider v-if="!loading" :value="number" @change="sliderChange" show-value step="1" :min='1'
					:max="cells.length" />
			</view>
		
		</view>
		
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,getCurrentInstance,
		onBeforeUnmount
	} from 'vue';
	const clockTimer = ref(null)
	const clockContext = ref(null)
	const requestAnimationFrame = ref(null)
	const upload = ()=>{
		achievementShow.value=false
		uni.navigateTo({
				url:'/mousegame/ranking'
			})
	}
	const canvasInit = () => {
		const ins = getCurrentInstance();
		const query = uni.createSelectorQuery().in(ins.proxy);


		query.select("#clockCanvas").fields({
			size: true,
			node: true
		}).exec((res) => {
			console.log(res, 'res');
			// Canvas 对象
			const canvas = res[0].node;
			canvas.width = 100
			canvas.height = 100
			clockContext.value = canvas.getContext("2d")
			// 这里可以执行 canvas 提供的方法
			// https://developers.weixin.qq.com/miniprogram/dev/api/canvas/Canvas.requestAnimationFrame.html
			requestAnimationFrame.value = canvas.requestAnimationFrame
			startClock()
			console.log('requestAnimationFrame', canvas.requestAnimationFrame);
		})
	}
	const startClock = () => {
		// clockTimer.value = setInterval(() => {
		// 	drawClock();
		// }, 1000);
		drawClock()
		requestAnimationFrame.value(startClock)
		// clockContext.value.requestAnimationFrame(drawClock)
	}
	const drawClock = () => {
		const ctx = clockContext.value;
	
		// 清空画布
		ctx.clearRect(0, 0, 100, 100);
	
		// 绘制表盘
		ctx.beginPath();
		// 圆的位置 
		const circularX = 50
		const circularY = 50
		// 圆的半径
		const circularR = circularX - 3
		// scale半径
		const scaleR = circularX - 23
		// clockwise半径
		const clockwiseR = circularX - 21
		// minuteHand半径
		const minuteHandR = circularX - 12
		// second半径
		const secondR = circularX - 9
		ctx.arc(circularX, circularY, circularR, 0, 2 * Math.PI); //第一、二个参数为表盘位置，第三个参数为表盘大小
		ctx.lineWidth = 1; //表盘线的粗细
		ctx.strokeStyle = '#000'; //表盘线的颜色
		ctx.stroke();
		
		ctx.beginPath();
		ctx.arc(circularX, circularY, 3, 0, 2 * Math.PI); //第三个参数为大小
		ctx.strokeStyle = '#000'; //时钟刻度颜色
		ctx.fill();
		ctx.stroke();
		// 画时刻度
			for(var i=0;i<12;i++){
				ctx.beginPath()
				ctx.save()
				ctx.translate(circularX,circularY)
				ctx.lineWidth=2
				ctx.strokeStyle='black'
				ctx.rotate(i*30*Math.PI/180)
				ctx.moveTo(0,-circularX+15)
				ctx.lineTo(0,-circularX + 5)
				ctx.stroke()
				ctx.restore()
				ctx.closePath()
			}
			 // 画分刻度
			for(var i=0;i<60;i++){
				ctx.beginPath()
				ctx.save()
				ctx.translate(circularX,circularY)
				ctx.lineWidth=1
				ctx.strokeStyle='black'
				ctx.rotate(i*6*Math.PI/180)
				ctx.moveTo(0,-circularX+10)
				ctx.lineTo(0,-circularX+5)
				ctx.stroke()
				ctx.restore()
				ctx.closePath()
			}
		
		// 绘制时钟刻度
		for (let i = 0; i < 12; i++) {
			ctx.setTransform(1, 0, 0, 1, 0, 0);
			ctx.translate(-4, 4);
			const angle = i * (Math.PI / 6) - Math.PI / 2;
			const x = circularX + Math.cos(angle) * scaleR; //时钟刻度X轴位置
			const y = circularY + Math.sin(angle) * scaleR; //时钟刻度Y轴位置
	
			// ctx.beginPath();
			// ctx.arc(x, y, 3, 0, 2 * Math.PI); //第三个参数为大小
			// ctx.strokeStyle = '#000'; //时钟刻度颜色
			// ctx.fill();
			ctx.font = "10px Verdana";
			// 创建渐变
			var gradient = ctx.createLinearGradient(0, 0, circularX, 0);
			
			gradient.addColorStop("1.0", "#000");
			// 用渐变填色
			ctx.fillStyle = gradient;
			ctx.fillText(i || 12, x, y);
		}
		ctx.setTransform(1, 0, 0, 1, 0, 0);
		// 获取当前时间
		const now = new Date();
		const hours = now.getHours();
		const minutes = now.getMinutes();
		const seconds = now.getSeconds();
	
		// 绘制时针
		const hourAngle = (hours % 12 + minutes / 60 + seconds / 3600) * (Math.PI / 6) - Math.PI / 2;
		const hourX = circularX + Math.cos(hourAngle) * clockwiseR; //时针X轴位置
		const hourY = circularY + Math.sin(hourAngle) * clockwiseR; //时针Y轴位置
	
		ctx.beginPath();
		ctx.lineWidth = 2 //时针的粗细
		ctx.strokeStyle = '#000'; //时针颜色
		ctx.moveTo(circularX, circularY); //时针围绕中心点
		ctx.lineTo(hourX, hourY);
		ctx.stroke();
	
		// 绘制分针
		const minuteAngle = (minutes + seconds / 60) * (Math.PI / 30) - Math.PI / 2;
		const minuteX = circularX + Math.cos(minuteAngle) * minuteHandR; //分针X轴位置
		const minuteY = circularY + Math.sin(minuteAngle) * minuteHandR; //分针Y轴位置
	
		ctx.beginPath();
		ctx.lineWidth = 1.5; //分针的粗细
		ctx.strokeStyle = '#000'; //分针颜色
		ctx.moveTo(circularX, circularY); //分针围绕中心点
		ctx.lineTo(minuteX, minuteY);
		ctx.stroke();
	
		// 绘制秒针
		const secondAngle = (seconds + now.getMilliseconds() / 1000) * (Math.PI / 30) - Math.PI / 2;
		const secondX = circularX + Math.cos(secondAngle) * secondR; //分针X轴位置
		const secondY = circularY + Math.sin(secondAngle) * secondR; //分针Y轴位置
	
		ctx.beginPath();
		ctx.lineWidth = 1; //分针的粗细
		ctx.strokeStyle = '#f00'; //分针颜色
		ctx.moveTo(circularX, circularY); //分针围绕中心点
		ctx.lineTo(secondX, secondY);
		ctx.stroke();
	
		// ctx.draw();
	}
	const score = ref(0);
	const number = ref(1);
	const time = ref(0);
	const cells = ref(Array(9).fill(false));
	let gameInterval = null;
	let timer = null;

	const startTimer = () => {
		if (timer) return; // 防止重复启动计时器
		time.value = 0;
		timer = setInterval(() => {
			time.value += 1;
		}, 1000);
	};

	const stopTimer = () => {
		clearInterval(timer);
		timer = null;
	};
	const hitSound = wx.createInnerAudioContext();
	hitSound.src = '/mousegame/static/cat.mp3'; // 确保音频文件路径正确
	const difficultyOfSwitching = (e) => {
		cells.value = Array(e).fill(false);
	}
	const sliderChange = (e) => {
		console.log('value 发生变化：' + e.detail.value)
		number.value = +e.detail.value
	}
	const randomCell = () => {
		const randomIndex = Math.floor(Math.random() * cells.value.length);
		if(cells.value[randomIndex] == true){
			
		}else{
			cells.value[randomIndex] = true;
			setTimeout(() => {
				cells.value[randomIndex] = false;
			}, number.value * 1000);
		}
		
	};
	let loading = ref(false)
	const achievementShow = ref(false)
	const achievement = ref('')
	const stop = () => {
		if(time.value&&score.value){
			achievement.value = `你在${time.value}秒内，打到了${score.value}只老鼠,手速${(score.value/time.value).toFixed(2)}`
			uni.setStorageSync('handSpeed', (score.value/time.value).toFixed(2))
			achievementShow.value = true
		}
		
		stopTimer()
		loading.value = false
		if (gameInterval) clearInterval(gameInterval);
		cells.value = cells.value.map((item) => {
			item = false
		})
	}
	const startGame = () => {
		if (loading.value) return
		startTimer()
		loading.value = true
		score.value = 0;
		if (gameInterval) clearInterval(gameInterval);

		gameInterval = setInterval(() => {
			for (let i = 0; i < number.value; i++) {
				randomCell();
			}

		}, 1000);
	};

	const hitMole = (index) => {
		if (cells.value[index]) {
			score.value += 1;
			cells.value[index] = false;
			hitSound.play();
		}
	};

	onMounted(() => {
		canvasInit()
		// Cleanup when the component is unmounted
		onBeforeUnmount(() => {
			if (gameInterval) clearInterval(gameInterval);
		});
	});
	const pageBg = ''
</script>

<style scoped lang="scss">
	.popup {
		padding: 50rpx;
		border-radius: 20rpx;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 700rpx;
		height: 500rpx;
		background-color: #FFF;
		z-index: 101;
		color: #000;
	}
	.clock {
		width: 100px;
		height: 100px;
	}
	.container {
		display: flex;
		flex-direction: column;
		// align-items: center;
		// justify-content: center;
		height: 100vh;
		background-color: #f0f0f0;
		
	}

	.score {
		font-size: 24px;
		margin-bottom: 20px;
	}

	.game-grid {
		display: grid;
		grid-template-columns: repeat(3, 100px);
		grid-gap: 10px;
	}

	.cell {
		width: 100px;
		height: 100px;
		background-color: #FFFFFF90;
		// 模糊	
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 5px;
		position: relative;
		cursor: pointer;
	}

	.mole {
		width: 80px;
		height: 80px;

		// background-color: brown;
		// border-radius: 50%;
		.mouse {
			width: 80px;
			height: 80px;
		}
	}

	.btn-box {
		margin-top: 100rpx;
	}

	.btn {
		width: 100rpx;
		height: 100rpx;
	}
</style>